<template>
  <a-modal v-model:visible="visible" width="auto" footer="false">
    <template #title>Pip 列表</template>
    <div id="modal-content">
      <div style="margin-bottom: 16px;">
        <a-input v-model="packageName" placeholder="请输入库名称" style="width: 200px; margin-right: 8px;" :disabled="installing"/>
        <a-select v-model="installSource" placeholder="请选择安装源" style="width: 200px; margin-right: 8px;" :disabled="installing">
          <a-option value="https://pypi.org/simple">PyPI</a-option>
          <a-option value="https://pypi.tuna.tsinghua.edu.cn/simple">清华大学</a-option>
          <a-option value="https://pypi.mirrors.ustc.edu.cn/simple">中国科学技术大学</a-option>
        </a-select>
        <a-button type="primary" @click="handleInstall" :loading="installing">安装</a-button>
      </div>

      <a-skeleton animation v-if="loadingList">
        <a-space direction="vertical" :style="{ width: '100%' }" size="large">
          <a-skeleton-line :rows="3" />
        </a-space>
      </a-skeleton>
      <ul v-else>
        <li v-for="item in pipList" :key="item.Package">
          {{ item.Package }} - {{ item.Version }}
        </li>
      </ul>

    </div>
    <template #footer>
      <span style="color: var(--color-text-4)">Copyright 2025 Coconut Studio</span>
    </template>
  </a-modal>
</template>

<script setup>
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'

const visible = ref(false)
const pipList = ref([
  // { Package: "pip", Version: "20.2.3" },
  // { Package: "setuptools", Version: "49.2.1" }
])
const packageName = ref('')
const installSource = ref('')
const loadingList = ref(false)
const installing = ref(false)

function handlePipClick() {
  visible.value = true
  fetchPipList()
}

async function fetchPipList() {
  loadingList.value = true;
  try {
    const response = await fetch('./api/pipList')
    const data = await response.json()
    pipList.value = data.pipList
  } catch (error) {
    Message.error('获取 Pip 列表失败')
    console.error('获取 Pip 列表失败:', error)
  } finally {
    loadingList.value = false;
  }
}

async function handleInstall() {
  installing.value = true;
  try {
    // 构造完整的 URL，将参数拼接到查询字符串中
    const url = new URL('/api/pipInstall', window.location.origin);
    url.searchParams.append('packageName', packageName.value);
    url.searchParams.append('installSource', installSource.value);

    // 发送 GET 请求
    const response = await fetch(url);

    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 解析响应数据
    const data = await response.json();
    console.log(data);
    packageName.value = "";
    Message.success('安装成功')
  } catch (error) {
    Message.error('安装失败')
    console.error('安装失败:', error);
  } finally {
    installing.value = false;
  }
}

defineExpose({ handlePipClick })
</script>

<style>
#modal-content {
  -webkit-tap-highlight-color: transparent;
}
</style>